/**
 * Created by Qingger Corp.
 * User: jsspf
 * Date: 2017/11/4
 * Time: 11:58
 */

// 函数类型
function add(x:number,y:number) : number {
    return x+y;
}

// 明确定义myAdd2的类型,注意参数和返回值之间用的是=>符号
let myAdd2 : (x:number,y:number) => number  = add;

// 函数变量,类型推断,可以省略myAdd的定义
let myAdd = function(x:number,y:number) :number {
    return x+y;
};

// 默认参数
function buildName(firstName:string,lastName='Smith') {
   return firstName + " " + lastName;
}

// 可省略参数
function buildName2(firstName:string,lastName?:string) {
    lastName = lastName ? lastName : 'Default';
    return firstName + " " + lastName;
}

// 剩余参数
function buildName3(firstName:string,...restOfName:string[]) {
    return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName3("Joseph", "Samuel", "Lucas", "MacKinzie");



/// 函数的this绑定
interface Card {
    suit : string,
    card  : number
}

interface Deck {
    suits : string[];
    cards : number[];
    createCardPicker(this:Deck) : ()=>Card;
}

let deck : Deck = {
    suits : ['hearts','spades','clubs','diamonds'],
    cards : Array(52),
    createCardPicker : function(this:Deck) {
        return () => {
            let pickedCard  = Math.floor(Math.random()*52);
            let pickedSuite = Math.floor(pickedCard/13);
            return {suit : this.suits[pickedSuite], card : pickedCard%13};
        }
    }
};

let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();



/// 函数重载
let suits = ["hearts","spades","clubs","diamonds"];
function pickCard(x:{suit:string,card:number}[]) : number;
function pickCard(x:number) : {suit:string;card:number};
function pickCard(x:any) : any {
   if(typeof x == "object") {
       return Math.floor(Math.random() * x.length);
   } else if (typeof x == "number") {
       let pickedSuite = Math.floor(x/13);
       return {suite:suits[pickedSuite] , card:x%13};
   }
}
let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }];
let pickedCard1 = myDeck[pickCard(myDeck)];
console.log("card: " + pickedCard1.card + " of " + pickedCard1.suit);

let pickedCard2 = pickCard(15);
console.log("card: " + pickedCard2.card + " of " + pickedCard2.suit);